<script setup lang="ts">
import { BASE_WS_URL } from "@/config/env";
import RFB from "@novnc/novnc/core/rfb";
import { onMounted, onUnmounted } from "vue";


const props = defineProps<{
    url: string,
    password?: string,
}>();

let rfb: any;
let desktopName: string;


const connectedToServer = (e: any) => {
    status("Connected to " + desktopName);
}

const disconnectedFromServer = (e: any) => {
    if (e.detail.clean) {
        status("Disconnected");
    } else {
        status("Something went wrong, connection is closed");
    }
}

const credentialsAreRequired = (e: any) => {
    const password = prompt("Password Required:");
    rfb.sendCredentials({ password: password });
}

const updateDesktopName = (e: any) => {
    desktopName = e.detail.name;
    document.getElementsByTagName("title")[0].innerText = desktopName;
}

const status = (text: string) => {
    console.log(text);
}

onMounted(() => {
    let url: string = BASE_WS_URL +"websockify/?token="+ props.url;
    try {
        rfb = new RFB(document.getElementById('screen'), url, { credentials: { password: props.password } });
        rfb.addEventListener("connect", connectedToServer);
        rfb.addEventListener("disconnect", disconnectedFromServer);
        rfb.addEventListener("credentialsrequired", credentialsAreRequired);
        rfb.addEventListener("desktopname", updateDesktopName);
        rfb.viewOnly = false;
        rfb.scaleViewport = false;
    } catch (e: any) {
        status(e);
    }
})

onUnmounted(() => {
    rfb.disconnect();
})

</script>

<template>
    <div id="screen"></div>
</template>